/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mdp.workflow.de.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.workflow.api.DeploymentModelService;
import com.mdp.workflow.de.entity.Model;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.*;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Tijs Rademakers
 * @author Joram Barrez
 */
@Service("mdp.workflow.de.DeploymentModelServiceImpl")
public class DeploymentModelServiceImpl implements DeploymentModelService {

  private static final Logger logger = LoggerFactory.getLogger(DeploymentModelServiceImpl.class);


  @Autowired
  protected ModelServiceImpl modelService;

  @Autowired
  protected RepositoryService repositoryService;
  

  @Autowired
  protected ObjectMapper objectMapper;


  @Override
  @Transactional
  public Deployment modelDeployment(Model model) {
    Deployment deployment = null;
    User user=LoginUtils.getCurrentUserInfo();
      DeploymentBuilder deploymentBuilder = repositoryService.createDeployment()
          .name(model.getName())
          .key(model.getModelKey()).tenantId(user.getBranchId());
        BpmnModel bpmnModel = modelService.getBpmnModel(model, new HashMap(), new HashMap()); 
        deploymentBuilder.category(bpmnModel.getTargetNamespace());
        Map<String, StartEvent> startEventMap = processNoneStartEvents(bpmnModel);
        
        for (Process process : bpmnModel.getProcesses()) {
          processUserTasks(process.getFlowElements(), process, startEventMap);
        }
        
        byte[] modelXML = modelService.getBpmnXML(bpmnModel);
        deploymentBuilder.addInputStream(model.getKey().replaceAll(" ", "") + ".bpmn", new ByteArrayInputStream(modelXML));
        deployment = deploymentBuilder.deploy();
      return deployment;
  }

  @Override
  @Transactional
  public void deleteDeployment(String deploymentKey) {
	  User user=LoginUtils.getCurrentUserInfo();
    // First test if deployment is still there, otherwhise the transaction will be rolled back
    List<Deployment> deployments = repositoryService.createDeploymentQuery().deploymentKey(String.valueOf(deploymentKey)).deploymentTenantId(user.getBranchId()).list();
    if (deployments != null) {
      for (Deployment deployment : deployments) {
        repositoryService.deleteDeployment(deployment.getId(), true);
      }
    }
  }

  protected Map<String, StartEvent> processNoneStartEvents(BpmnModel bpmnModel) {
    Map<String, StartEvent> startEventMap = new HashMap<String, StartEvent>();
    for (Process process : bpmnModel.getProcesses()) {
      for (FlowElement flowElement : process.getFlowElements()) {
        if (flowElement instanceof StartEvent) {
          StartEvent startEvent = (StartEvent) flowElement;
          if (CollectionUtils.isEmpty(startEvent.getEventDefinitions())) {
            if (StringUtils.isEmpty(startEvent.getInitiator())) {
              startEvent.setInitiator("initiator");
            }
            startEventMap.put(process.getId(), startEvent);
            break;
          }
        }
      }
    }
    return startEventMap;
  }

  protected void processUserTasks(Collection<FlowElement> flowElements, Process process, Map<String, StartEvent> startEventMap) {

    for (FlowElement flowElement : flowElements) {
      if (flowElement instanceof UserTask) {
        UserTask userTask = (UserTask) flowElement;
        if ("$INITIATOR".equals(userTask.getAssignee())) {
          if (startEventMap.get(process.getId()) != null) {
            userTask.setAssignee("${" + startEventMap.get(process.getId()).getInitiator() + "}");
          }
        }

      } else if (flowElement instanceof SubProcess) {
        processUserTasks(((SubProcess) flowElement).getFlowElements(), process, startEventMap);
      }
    }
  }

@Override
public Deployment modelDeployment(String modelId) {
	Model model=this.modelService.getModel(modelId);
	return this.modelDeployment(model); 
}

@Override
public void deleteDeploymentByPk(String deploymentId) {
	 repositoryService.deleteDeployment(deploymentId, true);
	
}
  
}
